package com.hspedu.homework.CorrectHomework01;

import com.hspedu.homework.Homework01.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DL5O
 * @version 1.0
 */
public class Server {
    public static void main(String[] args) throws IOException {
        String charset = "utf-8";
        String name = "nova";
        String hobby = "编写java程序";
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端，在9999端口监听,等待客户端连接...");
        Socket socket = serverSocket.accept();
        System.out.println("客户端:" + socket.getClass() + " 已连接");

        boolean loop = true;
        while(loop) {
            //接受客户端发来的消息
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset));
            String info = br.readLine();
            System.out.println("客服端发送的消息:" + info);

            //判断客户端发来的消息
            String data = "";
            if (info.equals("name")) {
                System.out.println("客户端获取名字...");
                data = "我是" + name;
            } else if (info.equals("hobby")) {
                System.out.println("客户端获取爱好...");
                data = "我的爱好" + hobby;
            } else if (info.equals("quit")) {
                System.out.println("客户端退出...");
                data = "quit";
                loop = false;

            } else {
                data = "你说啥呢？";
            }
            //往服务端发来的消息

            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, charset));
            if(loop == false){
                bw.write(data);
                bw.newLine();
                bw.flush();
                br.close();
                bw.close();
                break;
            }else {
                bw.write(data);
                bw.newLine();
                bw.flush();
            }
        }
        socket.close();
        System.out.println("服务端退出...");
    }
}
